#include "StdAfx.h"
#include "TrayIcon.h"

CTrayIcon::CTrayIcon(void) : m_hWnd(NULL), m_hIcon(NULL), m_nMsg(0), m_pTipStr(NULL)
{
}


CTrayIcon::~CTrayIcon(void)
{
	PNOTIFYICONDATA pData = GetIconData();
	Shell_NotifyIcon(NIM_DELETE, pData);
	if (m_pTipStr) delete [] m_pTipStr;
}


void CTrayIcon::Create(HWND hWnd, HICON hIcon, UINT nMsg, LPCTSTR pTipStr)
{
	m_hWnd = hWnd;
	m_hIcon = hIcon;
	m_nMsg = nMsg;
	if (pTipStr) Copy2TipStr(pTipStr);

	PNOTIFYICONDATA pData = GetIconData();
	Shell_NotifyIcon(NIM_ADD, pData);
}


void CTrayIcon::Update(HICON hIcon, LPCTSTR pTipStr)
{
	m_hIcon = hIcon;
	if (pTipStr) Copy2TipStr(pTipStr);

	PNOTIFYICONDATA pData = GetIconData();
	Shell_NotifyIcon(NIM_MODIFY, pData);
}


void CTrayIcon::Copy2TipStr(LPCTSTR pStr)
{
	if(m_pTipStr) delete [] m_pTipStr;
	UINT strLength = wcslen(pStr);
	m_pTipStr = new TCHAR[strLength + 1];
	wcscpy(m_pTipStr, pStr);
}


PNOTIFYICONDATA CTrayIcon::GetIconData()
{
	PNOTIFYICONDATA pData = new NOTIFYICONDATA;	
	ZeroMemory(pData, sizeof(NOTIFYICONDATA));

	pData->cbSize = sizeof(NOTIFYICONDATA);
	pData->hWnd = m_hWnd;
	pData->hIcon = m_hIcon;
	pData->uCallbackMessage = m_nMsg;

	UINT flags = NIF_MESSAGE | NIF_ICON;
	if (m_pTipStr)
	{
		flags |= NIF_TIP;
		wcscpy(pData->szTip, m_pTipStr);
	}

	pData->uFlags = flags;
	return pData;
}